import http from "http";
import fs from "fs";
import path from "path";
import mime from "mime";

http
  .createServer((req, res) => {
    const { method, url } = req;
    console.log(method, url);
    // 静态资源
    if (method === "GET" && (url === "/" || url.startsWith("/static"))) {
      // 获取绝对路径
      const staticPath = path.join(
        process.cwd(),
        url === "/" ? "static/index.html" : url
      );
      fs.readFile(staticPath, (err, content) => {
        if (err) {
          res.writeHead(404, {
            "Content-Type": "text/plain",
          });
          res.end("not found");
        } else {
          const type = mime.getType(staticPath);
          res.writeHead(200, {
            "Content-Type": type,
            "cache-control": "public, max-age=3600",
          });
          res.end(content);
        }
      });
    } else {
      res.end("hello");
    }
  })
  .listen(3000, () => {
    console.log("启动");
  });
